//
//  KLMineViewController.m
//  KunLun
//
//  Created by Mac on 2017/11/25.
//  Copyright © 2017年 stoneobs@icloud.com. All rights reserved.
//

#import "KLMineViewController.h"
#import "KLMIneTableViewCell.h"
#import "KLMenuControl.h"
#import "KLAboutUsViewController.h"
#import "KLSuggestViewController.h"
#import "KLSettingViewController.h"
#import "STDealRecordController.h"
#import "KLMessageViewController.h"
#import "KLCollectionViewController.h"
#import "KLOrderViewController.h"
#import "KLToBeshopViewController.h"
#import "KLMyShopViewController.h"
#import "KLSharePresentController.h"
#import "KLMyUploadViewController.h"
#import "KLMessageListViewController.h"
#import "KLMessageChatViewController.h"
#import "KLUserModel.h"
#import "KLChannelViewController.h"
#import "KLApplyToBeChannelController.h"
#import "KLFecthMoneyViewController.h"
#import "KLMyChannelViewController.h"
#import "STLocationManger.h"
#import "KLNewShouruViewController.h"
@interface KLMineViewController ()
//<EaseMessageViewControllerDelegate,EaseMessageViewControllerDataSource,IEMChatManager,EaseMessageViewControllerDelegate>
@property(nonatomic, strong) KLUserModel                     *userModel;
@property(nonatomic, strong) NSArray                     *dataSouce;
@property(nonatomic, strong) NSString                     *shareStr;
@property(nonatomic, strong) NSString                     *customServicePhone;
@property(nonatomic, strong) NSString                     *customServiceName;

@property(nonatomic, strong) KLMenuControl                     *moneyControl;
@property(nonatomic, strong) KLMenuControl                     *shouruControl;
@property(nonatomic, strong) STNoresultView                     *loginView;
@end

@implementation KLMineViewController

#pragma mark --vc 生命周期
- (void)viewDidLoad{
    [super viewDidLoad];
    self.view.backgroundColor = KL_backgroundColor;
//    [self st_setRightItemWithImage:[UIImage imageNamed:@"icon设置"]];
//    [self st_setLeftItemWithImage:[UIImage imageNamed:@"icon消息"]];

    self.title = @"我的";
    self.automaticallyAdjustsScrollViewInsets = NO;
    if (IOS11 && [self.tableView respondsToSelector:@selector(setContentInsetAdjustmentBehavior:)]) {
        [self.tableView setContentInsetAdjustmentBehavior:@(2)];
    }
    self.tableView.frame = CGRectMake(0, 0, UIScreenWidth, self.tabBarController.tabBar.top);
    [self configSubViewWithUser:nil];
    [self configDataSouce];
    [self sendShareRequest];
    [self sendCustomServerRequest];
    
    [[STLocationManger defult] startUpdatingLocationHande:^(STError *error, CLPlacemark *placemark) {
        if (placemark) {
            [[STLocationManger defult] updatePlacemarkWith:placemark];
        }
    }];
}
- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    NSString * token = [STUserManger defult].token;
    self.navigationController.navigationBar.barTintColor = [UIColor clearColor];
     self.navigationController.navigationBar.backgroundColor = [UIColor clearColor];
    [self.navigationController.navigationBar setBackgroundImage:[[UIImage alloc] init] forBarMetrics:UIBarMetricsDefault];
    [self.navigationController.navigationBar setShadowImage:[[UIImage alloc] init]];
    
    [self st_setLeftItemWithTitle:@"消息" titleColor:FlatWhite];
    [self st_setRightItemWithTitle:@"设置" titleColor:FlatWhite];
    [self sendMyInfoRequest];
}
- (void)viewDidAppear:(BOOL)animated{
    [super viewDidAppear:animated];
}
- (void)viewWillDisappear:(BOOL)animated{
    [super viewWillDisappear:animated];
    self.navigationController.navigationBar.barTintColor = KL_BlueBackGroundColor;
    self.navigationController.navigationBar.backgroundColor = KL_BlueBackGroundColor;
    [self.navigationController.navigationBar setBackgroundImage:nil forBarMetrics:UIBarMetricsDefault];
    [self.navigationController.navigationBar setShadowImage:nil];
}
- (void)viewDidDisappear:(BOOL)animated{
    [super viewDidDisappear:animated];
}

#pragma mark --subView
- (void)congifShoudLoginView{
    self.dataSouce = nil;
    self.tableView.userInteractionEnabled = NO;
    [self.tableView reloadData];
    self.loginView = [[STNoresultView alloc] initWithFrame:CGRectMake(0, 265, UIScreenWidth, 400) title:@"请重新登录" buttonTitle:@"登录" buttonHandle:^(NSString *titleString) {
        
        [[STUserManger defult] removeUserPreferce];
        [UIApplication sharedApplication].keyWindow.rootViewController = [[STNavigationController alloc] initWithRootViewController:[KLLoginViewController new]];
        [[UIApplication sharedApplication].keyWindow st_showAnimationWithType:STAnimationTypesuckEffect];
        
    }];
    [self st_setRightItemWithView:nil];
    [self st_setLeftItemWithView:nil];
    self.navigationItem.title = nil;
    [self.view addSubview:self.loginView];
}
- (void)configSubViewWithUser:(KLUserModel*)user{
     self.tableView.hidden = NO;
    UIImageView * imageView = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, UIScreenWidth, 260)];
    imageView.image = [UIImage imageNamed:@"mine_bg"];
    imageView.userInteractionEnabled = YES;
    //布局
    UIImageView * iconImageView = [[UIImageView alloc] initWithFrame:CGRectMake(20, 70, 70, 70)];
    iconImageView.image = [UIImage imageNamed:@"touxiang"];
    iconImageView.layer.cornerRadius = iconImageView.width / 2;
    iconImageView.clipsToBounds = YES;
    [imageView addSubview:iconImageView];
    
    STLabel * titleLable = [[STLabel alloc] initWithFrame:CGRectMake(iconImageView.right + 10, iconImageView.top + 10, UIScreenWidth - 20 - iconImageView.left, 15)
                                                     text:@"------"
                                                textColor:[UIColor whiteColor]
                                                     font:15
                                              isSizetoFit:NO
                                            textAlignment:NSTextAlignmentLeft];
    [imageView addSubview:titleLable];
    
    STLabel * numLable = [[STLabel alloc] initWithFrame:CGRectMake(iconImageView.right + 10, titleLable.bottom + 3, UIScreenWidth - 20 - iconImageView.left, 15)
                                                     text:@"--------"
                                                textColor:[UIColor whiteColor]
                                                     font:13
                                              isSizetoFit:NO
                                            textAlignment:NSTextAlignmentLeft];
    [imageView addSubview:numLable];
    
    STLabel * phoneLable = [[STLabel alloc] initWithFrame:CGRectMake(iconImageView.right + 10, numLable.bottom + 3, UIScreenWidth - 20 - iconImageView.left, 15)
                                                   text:@"----------"
                                              textColor:[UIColor whiteColor]
                                                   font:13
                                            isSizetoFit:NO
                                          textAlignment:NSTextAlignmentLeft];
    [imageView addSubview:phoneLable];
    
    UIView * bottomView = [[UIView alloc] initWithFrame:CGRectMake(0, imageView.height - 55, UIScreenWidth , 55)];
    bottomView.backgroundColor = [[UIColor whiteColor] colorWithAlphaComponent:0.1];
    [imageView addSubview:bottomView];
    
//    KLMenuControl * moneyControl = [[KLMenuControl alloc] initWithFrame:CGRectMake(0, 0, UIScreenWidth / 2, 55)
//                                                                  value:self.userModel.balance.length?self.userModel.balance:@"0"
//                                                                   name:@"余额"
//                                                               showLine:YES];
//    [bottomView addSubview:moneyControl];
//    self.moneyControl = moneyControl;
//    [moneyControl addTarget:self action:@selector(onSlectedMoneyControl) forControlEvents:UIControlEventTouchUpInside];
//
//    KLMenuControl * shouruControl = [[KLMenuControl alloc] initWithFrame:CGRectMake(moneyControl.right, 0, UIScreenWidth / 2, 55)
//                                                                   value:self.userModel.total.length?self.userModel.total:@"0"
//                                                                    name:@"收入"
//                                                                showLine:NO];
//    [bottomView addSubview:shouruControl];
//    self.shouruControl = shouruControl;
//    [shouruControl addTarget:self action:@selector(onSlectedShouruControl) forControlEvents:UIControlEventTouchUpInside];
    
    if (user) {
        [iconImageView sd_setImageWithURL:[NSURL URLWithString:user.header] placeholderImage:iconImageView.image];
        titleLable.text = user.nickname;

        phoneLable.text = user.username;
//        moneyControl.valueLable.text = user.balance;
//        shouruControl.valueLable.text = user.total;
    }
    numLable.hidden = YES;
    self.tableView.tableHeaderView = imageView;
}
- (void)configDataSouce{
    
    NSArray * sectionOne = @[
//                             [[STTableEasyModel alloc] initWithTextString:@"交易记录" imageName:@"交易记录"],
                             [[STTableEasyModel alloc] initWithTextString:@"匀加速订单" imageName:@"我的上传"],
                            // [[STTableEasyModel alloc] initWithTextString:@"我的收藏" imageName:@"我的收藏"],
                             [[STTableEasyModel alloc] initWithTextString:@"我的订单" imageName:@"我的订单"],
                             [[STTableEasyModel alloc] initWithTextString:@"我的渠道" imageName:@"我的渠道"],
                             [[STTableEasyModel alloc] initWithTextString:@"我的收入" imageName:@"交易记录"],
                             [[STTableEasyModel alloc] initWithTextString:@"推荐好友" imageName:@"推荐好友"],
                             [[STTableEasyModel alloc] initWithTextString:@"我的店铺" imageName:@"我的店铺"]];
    
    NSArray * sectionTwo = @[
                             [[STTableEasyModel alloc] initWithTextString:@"客服中心" imageName:@"客服中心"],
                             [[STTableEasyModel alloc] initWithTextString:@"关于我们" imageName:@"关于我们"],
                             [[STTableEasyModel alloc] initWithTextString:@"意见反馈" imageName:@"意见反馈"]
    ];
    self.dataSouce = @[sectionOne,sectionTwo];
}
#pragma --mark UITableViewDataSource
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    
    return self.dataSouce.count;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    
    return [self.dataSouce[section] count];
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    return 44;
}
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    
    return 10;
}
- (UIView*)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    return [UIView new];
}
- (UIView*)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section{
    return [UIView new];
}
- (UITableViewCell*)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    static NSString * reuseIdentifier =  @"cell";
    KLMIneTableViewCell * cell = [tableView dequeueReusableCellWithIdentifier:reuseIdentifier];
    if (!cell) {
        cell = [[KLMIneTableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:reuseIdentifier];
        
    }
    STTableEasyModel * model = self.dataSouce[indexPath.section][indexPath.row];
    cell.ghImageView.image = model.image;
    cell.lable.text = model.textString;
    return cell;
}
#pragma --mark UITableViewDelegate
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
     [self.tableView deselectRowAtIndexPath:indexPath animated:NO];
    
    STTableEasyModel * model = self.dataSouce[indexPath.section][indexPath.row];
    if ([model.textString isEqualToString:@"关于我们"]) {
        [self.navigationController pushViewController:[KLAboutUsViewController new] animated:YES];
    }
    if ([model.textString isEqualToString:@"意见反馈"]) {
        [self.navigationController pushViewController:[KLSuggestViewController new] animated:YES];
    }
    if ([model.textString isEqualToString:@"交易记录"]) {
        [self.navigationController pushViewController:[STDealRecordController new] animated:YES];
    }
    if ([model.textString isEqualToString:@"我的收藏"]) {
        [self.navigationController pushViewController:[KLCollectionViewController new] animated:YES];
    }
    if ([model.textString isEqualToString:@"我的订单"]) {
        [self.navigationController pushViewController:[KLOrderViewController new] animated:YES];
    }
    if ([model.textString isEqualToString:@"我的渠道"]) {
        if (self.userModel.channel_status.integerValue == 3) {
            [self.navigationController pushViewController:[KLMyChannelViewController new] animated:YES];
           // [SVProgressHUD showInfoWithStatus:@"您已经是渠道商了"];
        }else if (self.userModel.channel_status.integerValue == 2){
            [SVProgressHUD showInfoWithStatus:@"您申请的渠道商已经被拒绝，请重新申请"];
            [self.navigationController pushViewController:[KLApplyToBeChannelController new] animated:YES];
        }else if (self.userModel.channel_status.integerValue == 1){
             [SVProgressHUD showInfoWithStatus:@"您申请的渠道商正在审核中,请稍后"];
        } else{
            [self.navigationController pushViewController:[KLApplyToBeChannelController new] animated:YES];
        }
        
    }
    if ([model.textString isEqualToString:@"我的收入"]) {
        if (self.userModel.shops_id.integerValue !=0 || self.userModel.channel_status.integerValue == 3) {
            KLNewShouruViewController * vc = [KLNewShouruViewController new];
            vc.user = self.userModel;
            [self.navigationController pushViewController:vc animated:YES];
        }else{
            [SVProgressHUD showErrorWithStatus:@"您不是商家和渠道商，请申请成为商家或者渠道商"];
        }

    }
    if ([model.textString isEqualToString:@"我的店铺"]) {
        // [self.navigationController pushViewController:[KLToBeshopViewController new] animated:YES];
        if (self.userModel) {
            //0 非商家
            if (self.userModel.shops_id.integerValue !=0) {
                //已经是商家
                KLMyShopViewController * vc = [KLMyShopViewController new];
                vc.shops_id = [self.userModel.shops_id description];
                 [self.navigationController pushViewController:vc animated:YES];
            }else{
                 [self.navigationController pushViewController:[KLToBeshopViewController new] animated:YES];
            }
           

        }else{
            [SVProgressHUD showErrorWithStatus:@"获取用户信息失败，请刷新"];
        }

        
    }
    if ([model.textString isEqualToString:@"匀加速订单"]) {
        [self.navigationController pushViewController:[KLMyUploadViewController new] animated:YES];
    }
    if ([model.textString isEqualToString:@"客服中心"]) {
        if (!self.customServicePhone.length) {
            [self sendCustomServerRequest];
            return;
        }
        KLMessageChatViewController * vc = [[KLMessageChatViewController alloc] initWithConversationChatter:self.customServicePhone conversationType:EMConversationTypeChat];
        vc.title = self.customServiceName;
        
        [self.navigationController pushViewController:vc animated:YES];
    }
    
    
    if ([model.textString isEqualToString:@"推荐好友"]) {
        KLSharePresentController * vc = [[KLSharePresentController alloc] initWithHandle:^(NSString *chosedIde) {
            NSLog(@"%@",chosedIde);
            if (!self.shareStr.length) {
                [self sendShareRequest];
            }
            SendMessageToWXReq  *req = [SendMessageToWXReq new];
            req.text = self.shareStr;
            req.bText = YES;
            req.scene = WXSceneSession;
            if ([chosedIde isEqualToString:@"朋友圈"]) {
                req.scene = WXSceneTimeline;
            }
            [WXApi sendReq:req];
        }];
        [self presentViewController:vc animated:NO completion:nil];
    }
    
   
}

#pragma mark --Action Method
- (void)st_rightBarAction:(id)sender{
    KLSettingViewController * vc =  [KLSettingViewController new];
    vc.userModel = self.userModel;
    [self.navigationController pushViewController:vc animated:YES];
}
- (void)st_leftBarAction:(id)sender{
    KLMessageListViewController *chatListVC = [[KLMessageListViewController alloc] init];
    [self.navigationController pushViewController:chatListVC animated:YES];
}
- (void)onSlectedMoneyControl{
    KLFecthMoneyViewController * vc = [KLFecthMoneyViewController new];
    vc.money = self.userModel.balance;
    [self.navigationController pushViewController:vc animated:YES];
   // [self sendAlipayRequest];
    
}
- (void)onSlectedShouruControl{
   // [self sendWechatOrderRequest];
}

#pragma mark --NetWork Method
- (void)sendMyInfoRequest{
    NSMutableDictionary * dic = [NSMutableDictionary new];
    NSString * url = [NSString stringWithFormat:@"%@%@%@",serviceUrl,@"/api/user/userinfo",[NSString stringWithFormat:@"?token=%@",[STUserManger defult].token]];
    [[STNetWrokManger defaultClient] requestWithPath:url
                                              method:STHttpRequestTypePost
                                          parameters:dic
                                             success:^(NSURLSessionDataTask *operation, id responseObject) {
                                                 
                                                 NSDictionary * dataDic =  responseObject[@"data"];
                                                 if ([dataDic.allKeys containsObject:@"userinfo"]) {
                                                     KLUserModel * user = [KLUserModel mj_objectWithKeyValues:dataDic[@"userinfo"]];
                                                     self.userModel = user;
                                                     [[STUserManger defult] updateUserModel:self.userModel];
                                                     [self configSubViewWithUser:user];
                                                 }
                                                 
                                                 [self.tableView.mj_header endRefreshing];
                                                 [SVProgressHUD dismiss];
                                             } failure:^(NSString *stateCode, STError *error) {
                                                 
                                                 // [SVProgressHUD showErrorWithStatus:error.desc];
                                                 if (error.code == 2001) {
                                                     [self congifShoudLoginView];
                                                 }
                                                 [self.tableView.mj_header endRefreshing];
                                                 [SVProgressHUD dismiss];
                                             }];
}
- (void)sendWechatOrderRequest{
    [SVProgressHUD showWithStatus:@"正在加载"];
    NSString * url = [NSString stringWithFormat:@"%@%@%@",serviceUrl,@"/api/order/deposit?token=",[STUserManger defult].token];
    [[STNetWrokManger defaultClient] requestWithPath:url
                                              method:STHttpRequestTypePost
                                          parameters:@{@"type":@"wxpay"}
                                             success:^(NSURLSessionDataTask *operation, id responseObject) {
                                                 [SVProgressHUD dismiss];
                                                 
                                                 NSDictionary * dic = [responseObject valueForKey:@"data"];
                                                 NSDictionary * wechatDic = dic[@"pay_data"];
                                                 //wechat
                                                 PayReq *request = [PayReq new];
                                                 request.nonceStr = wechatDic[@"noncestr"];
                                                 request.package = wechatDic[@"package"];
                                                 request.partnerId = wechatDic[@"partnerid"];
                                                 request.prepayId = wechatDic[@"prepayid"];
                                                 request.sign = wechatDic[@"sign"];
                                                 request.timeStamp = [wechatDic[@"timestamp"] intValue];
                                                [WXApi sendReq:request];
                                                 
                                                 
                                             } failure:^(NSString *stateCode, STError *error) {
                                                 [SVProgressHUD dismiss];
                                                 [SVProgressHUD showErrorWithStatus:error.desc];
                                             }];
}
- (void)sendAlipayRequest{
    [SVProgressHUD showWithStatus:@"正在加载"];
    NSString * url = [NSString stringWithFormat:@"%@%@%@",serviceUrl,@"/api/order/deposit?token=",[STUserManger defult].token];
    [[STNetWrokManger defaultClient] requestWithPath:url
                                              method:STHttpRequestTypePost
                                          parameters:@{@"type":@"alipay"}
                                             success:^(NSURLSessionDataTask *operation, id responseObject) {
                                                 [SVProgressHUD dismiss];
                                                 
                                                 NSDictionary * dic = [responseObject valueForKey:@"data"];
                                                 NSString * alipayStr = dic[@"pay_data"];
                                                 //alipay
                                                 [[AlipaySDK defaultService] payOrder:alipayStr fromScheme:@"KunLun" callback:^(NSDictionary *resultDic) {
                                                     NSLog(@"reslut = %@",resultDic);
                                                     //回调在appdelegate 中
                                                 }];
                                                 
                                                 
                                             } failure:^(NSString *stateCode, STError *error) {
                                                 [SVProgressHUD dismiss];
                                                 [SVProgressHUD showErrorWithStatus:error.desc];
                                             }];
}
- (void)sendShareRequest{

    NSMutableDictionary * dic = [NSMutableDictionary new];
    NSString * url = [NSString stringWithFormat:@"%@%@",serviceUrl,@"/api/user/share"];
    [[STNetWrokManger defaultClient] requestWithPath:url
                                              method:STHttpRequestTypePost
                                          parameters:dic
                                             success:^(NSURLSessionDataTask *operation, id responseObject) {
                                                 [self.tableView.mj_header endRefreshing];
                                                 [SVProgressHUD dismiss];
                                                 NSDictionary * dataDic =  responseObject[@"data"];
                                                 NSLog(@"json = %@",dataDic.mj_JSONString);
                                                 if ([dataDic.allKeys containsObject:@"iOS_url"] && [dataDic.allKeys containsObject:@"android_url"]) {
                                                     
                                                     self.shareStr = [NSString stringWithFormat:@"iOS下载地址:%@,安卓下载地址:%@",dataDic[@"iOS_url"],dataDic[@"android_url"]];
                                                 }

                                                 
                                             } failure:^(NSString *stateCode, STError *error) {
                                                 [self.tableView.mj_header endRefreshing];
                                                 [SVProgressHUD dismiss];
                                                 [SVProgressHUD showErrorWithStatus:error.desc];
                                                 
                                                 
                                             }];
}
- (void)sendCustomServerRequest{
    
    NSMutableDictionary * dic = [NSMutableDictionary new];
    NSString * url = [NSString stringWithFormat:@"%@%@%@",serviceUrl,@"/api/user/service?token=",[STUserManger defult].token];
    [[STNetWrokManger defaultClient] requestWithPath:url
                                              method:STHttpRequestTypePost
                                          parameters:dic
                                             success:^(NSURLSessionDataTask *operation, id responseObject) {
                                                 [self.tableView.mj_header endRefreshing];
                                                 [SVProgressHUD dismiss];
                                                 NSArray * array =  responseObject[@"data"][@"list"];
                                                 NSDictionary * dataDic = array.firstObject;
                                                 NSLog(@"json = %@",dataDic.mj_JSONString);
                                                 if ([dataDic.allKeys containsObject:@"username"] && [dataDic.allKeys containsObject:@"nickname"] ) {
                                                     self.customServicePhone = dataDic[@"username"];
                                                     self.customServiceName = dataDic[@"nickname"];
                                                 }
                                                 
                                                 
                                             } failure:^(NSString *stateCode, STError *error) {
                                                 [self.tableView.mj_header endRefreshing];
                                                 [SVProgressHUD dismiss];
                                                 //[SVProgressHUD showErrorWithStatus:error.desc];
                                             }];
}
@end
